﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ZRT.RHPX.UI.Filters
{
    public class UserAuthorize : AuthorizeAttribute
    {
        /// <summary>
        /// 授权失败时呈现的视图
        /// </summary>
        public string AuthorizationFailView { get; set; }

        /// <summary>
        /// 请求授权时执行
        /// </summary>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //获得url请求里的controller和action：
            string controllerName = filterContext.RouteData.Values["controller"].ToString().ToLower();
            string actionName = filterContext.RouteData.Values["action"].ToString().ToLower();
            //string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            //string actionName = filterContext.ActionDescriptor.ActionName;

            ////根据请求过来的controller和action去查询可以被哪些角色操作:
            //Models.RoleWithControllerAction roleWithControllerAction = Database.SampleData.roleWithControllerAndAction.Find(r => r.ControllerName.ToLower() == controllerName && r.ActionName.ToLower() == actionName);
            //if (roleWithControllerAction != null)
            //{
            //    this.Roles = roleWithControllerAction.RoleIds;     //有权限操作当前控制器和Action的角色id
            //}
            base.OnAuthorization(filterContext);   //进入AuthorizeCore
        }

        /// <summary>
        /// 自定义授权检查（返回False则授权失败）
        /// </summary>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.User.Identity.IsAuthenticated)
            {
                //string userName = httpContext.User.Identity.Name;    //当前登录用户的用户名
                //Models.User user = Database.SampleData.users.Find(u => u.UserName == userName);   //当前登录用户对象

                //if (user != null)
                //{
                //    Models.Role role = Database.SampleData.roles.Find(r => r.Id == user.RoleId);  //当前登录用户的角色
                //    foreach (string roleid in Roles.Split(','))
                //    {
                //        if (role.Id.ToString() == roleid)
                //            return true;
                //    }
                //    return false;
                //}
                //else
                //    return false;
                return false;
            }
            else
                return false;     //进入HandleUnauthorizedRequest 
        }

        /// <summary>
        /// 处理授权失败的HTTP请求
        /// </summary>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new ViewResult { ViewName = AuthorizationFailView };
            //filterContext.Result = new RedirectResult("/Admin/Dashboard");
        }
    }
}